package android.medicalcloud.com.yiapp.yilian.ui.ac;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.medicalcloud.com.yiapp.R;
import android.medicalcloud.com.yiapp.base.activity.BaseActivity;
import android.medicalcloud.com.yiapp.base.cach.PreferceManager;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.StringTools;
import android.medicalcloud.com.yiapp.yilian.ui.view.dialog.RunProgressDialog;
import android.medicalcloud.com.yiapp.yilian.utils.android.Common;
import android.medicalcloud.com.yiapp.yilian.utils.android.DialogFacory;
import android.medicalcloud.com.yiapp.yilian.utils.android.FileUtils;
import android.medicalcloud.com.yiapp.yilian.utils.android.ImageLoader;
import android.medicalcloud.com.yiapp.yilian.utils.android.IntentTool;
import android.medicalcloud.com.yiapp.yilian.utils.android.ToastTool;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.bither.util.NativeUtil;

import java.io.File;

/**
 * Created by User on 2016/12/4.
 */
public class AvatarActivity extends BaseActivity implements View.OnClickListener {
    ImageView avatarImage;
    TextView takePhotoTv;
    TextView selectPhotoTv;
    TextView cancelTv;
    private static final int SELECT_IMAGE_RESULT_CODE = 999;
    private static final int CAPTURE_IMAGE_RESULT_CODE = 1000;
    private Uri mImageCaptureUri;
    private static final int CROP_IMAGE_RESULT = 1020;
    RunProgressDialog copressdialog;

    @Override
    protected void initView() {

        avatarImage = (ImageView)findViewById(R.id.avatarImage);
        takePhotoTv = (TextView)findViewById(R.id.takePhotoTv);
        selectPhotoTv = (TextView)findViewById(R.id.selectPhotoTv);
        cancelTv = (TextView)findViewById(R.id.cancelTv);
        copressdialog = DialogFacory.getInstance().createProgressRunDialog(this, "图片处理中,请耐心等候.");

        avatarImage.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Common.screenWidth(this)));
    }

    @Override
    protected void initEvent() {
        takePhotoTv.setOnClickListener(this);
        selectPhotoTv.setOnClickListener(this);
        cancelTv.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        String url = getIntent().getStringExtra("url");
        ImageLoader.getInstance(this, R.drawable.default_image).displayCileImage(url, avatarImage);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_avater;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancelTv:
                finish();
                break;
            case R.id.selectPhotoTv:
                selectFileFromLocal();
                break;
            case R.id.takePhotoTv:
                selectTakeCameraIndex();
                break;
        }
    }

    /**
     * 选择文件
     */
    private void selectFileFromLocal() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
    }

    private void selectTakeCameraIndex() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageCaptureUri = Uri.fromFile(new File(FileUtils.getCacheDirectory(this),
                "pick_photo_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        startActivityForResult(intent, CAPTURE_IMAGE_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String path = "";
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_IMAGE_RESULT_CODE) {
                path = getImageAbsolutePath(data.getData());
            }
            if (requestCode == CAPTURE_IMAGE_RESULT_CODE) {
                path = mImageCaptureUri.getPath();
            }
            if (!new File(path).exists()) {
                Toast.makeText(AvatarActivity.this,"image is null",Toast.LENGTH_LONG).show();
                return;
            }

            new CompressAysThread(path).execute("");
        }

    }

    private class CompressAysThread extends AsyncTask {
        String selectImages;
        String dir = "";
        String realPath;

        public CompressAysThread(String selectImages) {
            this.selectImages = selectImages;
            dir = FileUtils.createSDDir("image").getAbsolutePath();

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            if (!copressdialog.isShowing()) {
//            copressdialog.show();
//            }

        }

        @Override
        protected Object doInBackground(Object[] params) {
            try {
//                for (String string : selectImages) {
                int androidCompressImageLength = 0;
                try {
                    androidCompressImageLength = Integer.parseInt(PreferceManager.getInsance().getValueBYkey("androidCompressImageLength"));

                } catch (Exception e) {

                }
                Logger.e("--doInBackground--" + new File(selectImages).length());
                Logger.e("string=2=" + new File(selectImages).length());
                if (new File(selectImages).length() > androidCompressImageLength) {
                    Logger.e("string=1=" + selectImages);
                    String fileName = dir + "/" + new File(selectImages).getName();
                    Logger.e("string=2=" + fileName);
                    int q = 50;
                    try {
                        q = Integer.parseInt(PreferceManager.getInsance().getValueBYkey("q"));

                    } catch (Exception e) {

                    }
                    Logger.e("qqqqqqqqqqqqqq" + q);
                    NativeUtil.compressBitmap(BitmapFactory.decodeFile(selectImages), q,
                            fileName, false);

                    Logger.e("string=2111=" + new File(selectImages).length());
                    realPath = fileName;
                } else {
                    realPath = selectImages;
                }


//                }
            } catch (Exception e) {

            }

            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (StringTools.isNullOrEmpty(realPath)) {
                realPath = selectImages;
            }
            finish();
            ImageLoader.getInstance(AvatarActivity.this).displayLocalImage(realPath, avatarImage);
            IntentTool.startCropImage(AvatarActivity.this, realPath, 300, 300, CROP_IMAGE_RESULT);
//            if (copressdialog.isShowing()) {
//            copressdialog.dismiss();
//            }
        }
    }

    public String getImageAbsolutePath(Uri imageUri) {
        if (imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(this, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(this, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(this, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(this, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
